package com.ktjy.goods.service.impl;

import com.ktjy.goods.domain.TGoodsCategory;
import com.ktjy.goods.mapper.TGoodsCategoryMapper;
import com.ktjy.goods.service.ITGoodsCategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2025-03-15
 */
@Service
public class TGoodsCategoryServiceImpl extends ServiceImpl<TGoodsCategoryMapper, TGoodsCategory> implements ITGoodsCategoryService {

    @Autowired
    private TGoodsCategoryMapper goodsCategoryMapper;

    @Override
    public List<TGoodsCategory> getCategoryTree() {
        List<TGoodsCategory> allCategories = goodsCategoryMapper.selectList(null);

        // 构建一级分类列表
        List<TGoodsCategory> rootCategories = allCategories.stream()
                .filter(category -> category.getParentId() == 0)
                .collect(Collectors.toList());

        // 递归构建子分类
        rootCategories.forEach(category -> {
            category.setChildren(buildChildren(category.getId(), allCategories));
        });
        return rootCategories;
    }

    private List<TGoodsCategory> buildChildren(Long parentId, List<TGoodsCategory> allCategories) {
        return allCategories.stream()
                .filter(category -> category.getParentId().equals(parentId))
                .peek(category -> category.setChildren(buildChildren(category.getId(), allCategories)))
                .collect(Collectors.toList());
    }
}
